/*
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 */

/*
 *
 *
 *
 *
 *
 * Written by Doug Lea with assistance from members of JCP JSR-166
 * Expert Group and released to the public domain, as explained at
 * http://creativecommons.org/publicdomain/zero/1.0/
 */

package java.util.concurrent;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;


public abstract class CyclicBarrier{
    /**
     * 每个barrier都表示为一个generation实例。当barrier触发trip条件或重置时generation随之改变。
     * 使用barrier时有很多generation与线程关联-由于不确定性的方式，锁可能分配给等待的线程。
     * 但是在同一时间只有一个是活跃的generation(通过count变量确定)，并且其余的要么被销毁，要么被trip条件等待。
     * 如果有一个中断，但没有随后的重置，就不需要有活跃的generation。
     */
    private static class Generation {
        boolean broken = false;
    }

    private final ReentrantLock lock = new ReentrantLock();
    private final Condition trip = lock.newCondition();
    private final int parties;
    //所有线程到达barrier，运行barrierCommand
    private final Runnable barrierCommand;
    private Generation generation = new Generation();

    //等待到达barrier的参与线程数量，count=0 -> tripped
    private int count;

    //更新barrier状态并唤醒所有线程
    private void nextGeneration() {
        // signal completion of last generation
        trip.signalAll();
        // set up next generation
        count = parties;
        generation = new Generation();
    }

    //销毁当前barrier的generation，并唤醒所有线程
    private void breakBarrier() {
        generation.broken = true;
        count = parties;
        trip.signalAll();
    }

    private int dowait(boolean timed, long nanos)
        throws InterruptedException, BrokenBarrierException,
               TimeoutException {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            //当前generation的引用
            final Generation g = generation;
            //意思就是被打断了 ，得抛出异常
            if (g.broken)
                throw new BrokenBarrierException();
            //如果当前线程被中断了
            if (Thread.interrupted()) {
                //终止阻塞，唤醒所有线程
                breakBarrier();
                //抛出中断异常
                throw new InterruptedException();
            }
            //参与本次阻塞的线程数量-1，并赋值给index
            int index = --count;
            //这个时候，说明线程到齐了，应该放行了
            if (index == 0) {
                boolean ranAction = false;
                try {
                    final Runnable command = barrierCommand;
                    //如果有barrierCommand，在所有parties到达之后运行它
                    if (command != null)
                        command.run();
                    ranAction = true;
                    //开启新的一代
                    //1.唤醒trip条件队列内挂起的线程，被唤醒的线程 会依次 获取到lock，然后依次退出await方法。
                    //2.重置count 为 parties
                    //3.创建一个新的generation对象，表示新的一代
                    nextGeneration();
                    return 0;
                } finally {
                    if (!ranAction)
                        //唤醒所有线程
                        breakBarrier();
                }
            }

            //自旋等待 所有parties到达 | generation被销毁 | 线程中断 | 超时
            for (;;) {
                try {
                    //如果没有超时时间，那就进入aqs的条件队列了
                    if (!timed)
                        trip.await();
                    else if (nanos > 0L)
                        nanos = trip.awaitNanos(nanos);
                } catch (InterruptedException ie) {
                    if (g == generation && ! g.broken) {
                        breakBarrier();
                        throw ie;
                    } else {
                        Thread.currentThread().interrupt();
                    }
                }
                //如果外界施法中断，那就抛异常
                if (g.broken)
                    throw new BrokenBarrierException();
                //唤醒后，执行到这里，有几种情况？
                //1.正常情况，当前barrier开启了新的一代（trip.signalAll()）
                //3.当前线程trip中等待超时，然后主动转移到 阻塞队列 然后获取到锁 唤醒。

                //条件成立：说明当前线程挂起期间，最后一个线程到位了，然后触发了开启新的一代的逻辑，此时唤醒trip条件队列内的线程。
                if (g != generation)
                    return index;
                //唤醒后，执行到这里，有几种情况？
                //3.当前线程trip中等待超时，然后主动转移到 阻塞队列 然后获取到锁 唤醒。
                if (timed && nanos <= 0L) {
                    breakBarrier();//超时，销毁当前barrier
                    throw new TimeoutException();
                }
            }
        } finally {
            lock.unlock();
        }
    }

    //构造函数，指定参与线程数，并在所有线程到达barrier之后执行给定的barrierAction逻辑
    public CyclicBarrier(int parties, Runnable barrierAction) {
        if (parties <= 0) throw new IllegalArgumentException();
        this.parties = parties;
        this.count = parties;
        this.barrierCommand = barrierAction;
    }

    //构造函数，指定参与线程数
    public CyclicBarrier(int parties) {
        this(parties, null);
    }

    //获取参与等待到达barrier的线程数
    public int getParties() {
        return parties;
    }

    //等待所有的参与者到达barrier
    public int await() throws InterruptedException, BrokenBarrierException {
        try {
            return dowait(false, 0L);
        } catch (TimeoutException toe) {
            throw new Error(toe); // cannot happen
        }
    }

    //等待所有的参与者到达barrier，或等待给定的时间
    public int await(long timeout, TimeUnit unit)
        throws InterruptedException,
               BrokenBarrierException,
               TimeoutException {
        return dowait(true, unit.toNanos(timeout));
    }

    //查询barrier是否处于broken状态
    public boolean isBroken() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return generation.broken;
        } finally {
            lock.unlock();
        }
    }

    //重置barrier为初始状态
    public void reset() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            breakBarrier();   // break the current generation
            nextGeneration(); // start a new generation
        } finally {
            lock.unlock();
        }
    }

    //返回等待barrier的线程数量
    public int getNumberWaiting() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return parties - count;
        } finally {
            lock.unlock();
        }
    }
}
